<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单号">
              <a-input placeholder="请输入订单号" v-model="queryParam.orderNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="操作类型">
              <j-dict-select-tag
                placeholder="请选择操作类型"
                v-model="queryParam.operationType"
                dictCode="finished_goods_operation_type"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="关联单号">
              <a-input placeholder="请输入关联单号" v-model="queryParam.relatedDocNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="操作员">
              <a-input placeholder="请输入操作员姓名" v-model="queryParam.operatorName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item label="操作时间">
              <a-range-picker
                style="width: 100%"
                v-model="operateTimeRange"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                @change="onOperateTimeChange"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExport">导出</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1600, y: 500 }"
        @change="handleTableChange"
      >
        <template slot="operationTypeSlot" slot-scope="text">
          <a-tag :color="getOperationTypeColor(text)">
            <j-dict-label :value="text" dictCode="finished_goods_operation_type" />
          </a-tag>
        </template>

        <template slot="operationQuantitySlot" slot-scope="text, record">
          <span :style="{ color: getQuantityColor(record.operationType, text) }">
            {{ getQuantityPrefix(record.operationType) }}{{ text }}
          </span>
        </template>

        <template slot="operateTimeSlot" slot-scope="text">
          <span>{{ text ? formatDateTime(text) : '-' }}</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDictLabel from '@/components/dict/JDictLabel'
import { downFile } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'FinishedGoodsInventoryHistoryList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDictLabel,
  },
  data() {
    return {
      description: '成品库存变更记录',
      // 查询条件
      queryParam: {
        orderNo: '',
        operationType: '',
        relatedDocNo: '',
        operatorName: '',
        operateTimeStart: '',
        operateTimeEnd: '',
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '订单号',
          align: 'center',
          dataIndex: 'orderNo',
          width: 150,
        },
        {
          title: '操作类型',
          align: 'center',
          dataIndex: 'operationType',
          width: 100,
          scopedSlots: { customRender: 'operationTypeSlot' },
        },
        {
          title: '操作数量',
          align: 'center',
          dataIndex: 'operationQuantity',
          width: 100,
          scopedSlots: { customRender: 'operationQuantitySlot' },
        },
        {
          title: '操作前数量',
          align: 'center',
          dataIndex: 'beforeQuantity',
          width: 100,
        },
        {
          title: '操作后数量',
          align: 'center',
          dataIndex: 'afterQuantity',
          width: 100,
        },
        {
          title: '操作原因',
          align: 'center',
          dataIndex: 'operationReason',
          width: 150,
          ellipsis: true,
        },
        {
          title: '关联单号',
          align: 'center',
          dataIndex: 'relatedDocNo',
          width: 150,
        },
        {
          title: '操作员',
          align: 'center',
          dataIndex: 'operatorName',
          width: 100,
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 150,
          scopedSlots: { customRender: 'operateTimeSlot' },
        },
      ],
      url: {
        list: '/wms/finished-goods/inventory-log/records',
        exportXlsUrl: '/wms/finished-goods/inventory-log/exportXls',
      },
      operateTimeRange: [], // 操作时间范围
      toggleSearchStatus: false, // 控制查询区域的展开/收起状态
    }
  },
  created() {
    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    // 重写searchReset方法，确保重置所有查询条件
    searchReset() {
      this.queryParam = {
        orderNo: '',
        operationType: '',
        relatedDocNo: '',
        operatorName: '',
        operateTimeStart: '',
        operateTimeEnd: '',
      }
      this.operateTimeRange = []
      this.loadData(1)
    },

    // 重写getQueryParams方法，处理日期格式
    getQueryParams() {
      let params = Object.assign({}, this.queryParam)

      // 处理日期范围
      if (this.operateTimeRange && this.operateTimeRange.length === 2) {
        params.operateTimeStart = this.operateTimeRange[0].format('YYYY-MM-DD 00:00:00')
        params.operateTimeEnd = this.operateTimeRange[1].format('YYYY-MM-DD 23:59:59')
      } else {
        params.operateTimeStart = ''
        params.operateTimeEnd = ''
      }

      // 分页参数
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize

      return params
    },

    // 处理操作时间变化
    onOperateTimeChange(date, dateString) {
      if (date && date.length === 2) {
        this.queryParam.operateTimeStart = date[0].format('YYYY-MM-DD 00:00:00')
        this.queryParam.operateTimeEnd = date[1].format('YYYY-MM-DD 23:59:59')
      } else {
        this.queryParam.operateTimeStart = ''
        this.queryParam.operateTimeEnd = ''
      }
    },

    // 导出
    handleExport() {
      let params = this.getQueryParams()

      // 调用导出接口
      this.loading = true
      downFile(this.url.exportXlsUrl, params)
        .then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), '成品库存变更记录.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '成品库存变更记录.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 格式化日期时间
    formatDateTime(timestamp) {
      return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },

    // 获取操作类型颜色
    getOperationTypeColor(type) {
      const typeNum = parseInt(type)
      switch (typeNum) {
        case 1:
          return 'green' // 入库
        case 2:
          return 'red' // 出库
        case 3:
          return 'blue' // 调整
        case 4:
          return 'orange' // 预留
        case 5:
          return 'purple' // 释放
        default:
          return 'default'
      }
    },

    // 获取数量颜色
    getQuantityColor(operationType, quantity) {
      const typeNum = parseInt(operationType)
      if (typeNum === 1 || typeNum === 5) {
        // 入库、释放
        return '#52c41a' // 绿色
      } else if (typeNum === 2 || typeNum === 4) {
        // 出库、预留
        return '#f5222d' // 红色
      } else {
        // 调整
        return quantity > 0 ? '#52c41a' : '#f5222d'
      }
    },

    // 获取数量前缀
    getQuantityPrefix(operationType) {
      const typeNum = parseInt(operationType)
      if (typeNum === 1 || typeNum === 5) {
        // 入库、释放
        return '+'
      } else if (typeNum === 2 || typeNum === 4) {
        // 出库、预留
        return '-'
      } else {
        // 调整
        return ''
      }
    },

    // 切换查询区域展开/收起
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/common.less';

</style>
